package com.ymm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ymm.domain.entity.Exam;
import com.ymm.domain.entity.HtVo;
import com.ymm.domain.vo.ResponseResult;
import com.ymm.enums.AppHttpCodeEnum;
import com.ymm.exception.SystemException;
import com.ymm.mapper.ExamMapper;
import com.ymm.service.ExamService;
import com.ymm.utils.BeanCopyUtils;
import com.ymm.utils.security.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * (Exam)表服务实现类
 *
 * @author 椰咩咩咩
 * @since 2023-04-10 21:36:55
 */
@Service("examService")
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam> implements ExamService {

    @Override
    public ResponseResult getExamList() {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Exam> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Exam::getUserId, userId);
        wrapper.orderByAsc(Exam::getAcademicYear);
        List<Exam> exams = list(wrapper);
        return ResponseResult.okResult(exams);
    }

    @Override
    public ResponseResult addExam(Exam exam) {
        if (!StringUtils.hasText(exam.getAcademicYear())) {
            throw new SystemException(AppHttpCodeEnum.ACADEMIC_YEAR_NOT_NULL);
        }
        //判断该学年是否已经添加过了
        LambdaQueryWrapper<Exam> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Exam::getUserId, SecurityUtils.getUserId());
        wrapper.eq(Exam::getAcademicYear, exam.getAcademicYear());
        List<Exam> exams = list(wrapper);
        if (exams.size() > 0) {
            throw new SystemException(AppHttpCodeEnum.ACADEMIC_YEAR_HAS_EXIST);
        }
        exam.setUserId(SecurityUtils.getUserId());
        save(exam);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getHW() {
        LambdaQueryWrapper<Exam> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Exam::getAcademicYear);
        List<Exam> exams = list(wrapper);
        List<HtVo> htVos = BeanCopyUtils.copyBeanList(exams, HtVo.class);
        return ResponseResult.okResult(htVos);
    }

}

